package com.halflife.comeElectricity.member.rider;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.ValidSMSResult;
import cn.jsms.api.common.SMSClient;
import cn.jsms.api.common.model.SMSPayload;
import com.alibaba.fastjson.JSON;
import com.halflife.comeElectricity.admin.DateUtil;
import com.halflife.comeElectricity.basic.datadic.*;
import com.halflife.comeElectricity.batteryBox.LockerResult;
import com.halflife.comeElectricity.batteryBox.LockerResultItem;
import com.halflife.comeElectricity.batteryCabinet.BatteryCabinet;
import com.halflife.comeElectricity.batteryCabinet.BatteryCabinetAdminController;
import com.halflife.comeElectricity.batteryCabinet.BatteryCabinetRepository;
import com.halflife.comeElectricity.orderMng.order.Order;
import com.halflife.comeElectricity.orderMng.order.OrderEnum;
import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.ErrorCode;
import com.halflife.framework.domain.Page;
import com.halflife.framework.exception.BusinessException;
import com.halflife.comeElectricity.member.merchant.LoginService;
import com.halflife.framework.msg.RongHeSmsClientSend;
import com.halflife.framework.participant.Company;
import com.halflife.framework.participant.CompanyRepository;
import com.halflife.framework.participant.Department;
import com.halflife.framework.participant.DepartmentRepository;
import com.halflife.framework.utils.ImageUploadUtil;
import com.halflife.pay.wxpay.AESUtil;
import com.halflife.pay.wxpay.WXPayAgent;
import com.halflife.shiro.utils.ShiroUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhaoyf on 2018/2/25.
 */
@RestController
@RequestMapping("rider_login")
public class RiderLoginController {
    private Logger log = LoggerFactory.getLogger(RiderLoginController.class);
    @Resource
    private RiderRepository riderRepository;
    @Resource
    private DepositRepository depositRepository;
    @Resource
    private ChargeRepository chargeRepository;
    @Resource
    private DiscountRepository discountRepository;
    @Resource
    private DiscountLogRepository discountLogRepository;
    @Resource
    private PayLogRepository payLogRepository;
    @Resource
    private LoginService loginService;
    @Resource
    private DataDicRepository dataDicRepository;
    @Resource
    private DepartmentRepository departmentRepository;
    @Resource
    private CompanyRepository companyRepository;
    @Resource
    private BatteryCabinetRepository batteryCabinetRepository;

    @Resource
    private RentTypeRepository rentTypeRepositoty;
    @Resource
    private RefundLogRepository refundLogRepository;

    @GetMapping("/{id}")
    public Rider getRider(@PathVariable Integer id, @RequestParam(value = "name", required = false, defaultValue = "") String name) {
        Rider rider = riderRepository.selectByPrimaryKey(id);
        if (rider.getCompanyId() != null) {
            if (rider.getJhDate() == null) {
                rider.setJh(false);
            }else{
                if (new Date().getTime() > rider.getJhDate()) {
                    rider.setJh(false);
                }
            }

        }
        if (rider != null) {
            UsernamePasswordToken token = new UsernamePasswordToken(rider.getUnionid(), rider.getId().toString(), false);
            SecurityUtils.getSubject().login(token);
            ShiroUtil.setRider(rider);
        }
        return rider;
    }
    @GetMapping("/payType/{id}")
    public ResponseEntity<Object> getPayType(@PathVariable Integer id, @RequestParam(value = "name", required = false, defaultValue = "") String name) {
        Rider rider = riderRepository.selectByPrimaryKey(id);
        if (rider != null) {
            if (rider.getState() < 1) {
                return new ResponseEntity<Object>(ErrorCode.defaultInstance("您还没有核准激活,请联系商家"), HttpStatus.BAD_GATEWAY);
            }
            Map map = new HashMap();
            map.put("departmentId", rider.getDepartmentId());
            map.put("rentTypeId", rider.getRentType());
            map.put("valid", true);
            map.put("orderSql", "t.id desc");
            List<Charge> list = chargeRepository.selectAll(map);
            rider.setPayTypeList(list);

            map.put("riderId", rider.getId());
            map.put("status", 0);
            map.put("catagory", 1);
            Date now = new Date();
            long nowtime = now.getTime();
            map.put("endSql","(t.endDate is null or t.endDate ='' or t.endDate>"+nowtime+")");
            List<DiscountLog> discountLogs = discountLogRepository.selectAll(map);
            map.clear();
            map.put("riderId", rider.getId());
            map.put("catagory", "充值");
            int count =payLogRepository.selectCount(map);
            if (count < 1) {
                List<DiscountLog> discountLogs_ = new ArrayList<>();
                discountLogs.forEach(discountLog -> {
                    if (discountLog.getDiscount().getFirstValid()) {
                        discountLogs_.add(discountLog);
                    }
                });
                rider.setDiscountLogList(discountLogs_);
            }else{
                rider.setDiscountLogList(discountLogs);
            }
        }
        return new ResponseEntity<Object>(rider,HttpStatus.OK);
    }
    @GetMapping("/disCount/{id}")
    public ResponseEntity<Object> getDiscount(@PathVariable Integer id, @RequestParam(value = "catagory", required = false, defaultValue = "") String catagory) {
        Rider rider = riderRepository.selectByPrimaryKey(id);
        if (rider != null) {
            if (rider.getState() < 1) {
                return new ResponseEntity<Object>(ErrorCode.defaultInstance("您还没有核准激活,请联系商家"), HttpStatus.BAD_GATEWAY);
            }
            Map map = new HashMap();
            map.put("departmentId", rider.getDepartmentId());
            map.put("valid", true);
            map.put("orderSql", "t.id desc");
            map.put("riderId", rider.getId());
            map.put("catagory", catagory);
            List<DiscountLog> discountLogs = discountLogRepository.selectAll(map);
            rider.setDiscountLogList(discountLogs);
        }
        return new ResponseEntity<Object>(rider,HttpStatus.OK);
    }
    @GetMapping("/rentType/{id}")
    public ResponseEntity<Object> getRentType(@PathVariable Integer id) {
        Rider rider = riderRepository.selectByPrimaryKey(id);
        List<RentType> rentTypeList=new ArrayList<>();
        if (rider != null) {

            Map map = new HashMap();
            map.put("valid", true);
            map.put("orderSql", "t.id ");
            rentTypeList = rentTypeRepositoty.selectAll(map);
        }
        return new ResponseEntity<Object>(rentTypeList,HttpStatus.OK);
    }
    @GetMapping("/disCount/newLink/{id}")
    public ResponseEntity<Object> getNewLinkDiscount(@PathVariable Integer id) {
        Discount discount = null;
        Rider rider = riderRepository.selectByPrimaryKey(id);
        if (rider != null) {
//            if (rider.getState() < 1) {
//                return new ResponseEntity<Object>(ErrorCode.defaultInstance("您还没有核准激活,请联系商家"), HttpStatus.BAD_GATEWAY);
//            }
            Map map = new HashMap();
            map.put("departmentId", rider.getDepartmentId());
            map.put("valid", true);
            map.put("orderSql", "t.id desc");
            map.put("code", "guding-laodaixin");
            map.put("catagory", "1");
            List<Discount> discounts = discountRepository.selectAll(map);
            if(discounts.size()>0)
                discount = discounts.get(0);
        }
        return new ResponseEntity<Object>(discount,HttpStatus.OK);
    }

    public  Map getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx4e05fa2d7f448ba7&secret=db3541d806ae9e071a552cdee54c285c";
        RestTemplate template = new RestTemplate();
        Map  tokenMap = template.getForObject(url, HashMap.class);
        return tokenMap;
    }
    @GetMapping("/disCount/newLinks/{id}")
    public void getNewLinkDiscounts(@PathVariable Integer id,HttpServletResponse response) throws Exception{
        Discount discount = null;
        Rider rider = riderRepository.selectByPrimaryKey(id);
        if (rider != null) {
            Map tokenMap =this.getAccessToken();
            Map map = new HashMap();
            map.put("departmentId", rider.getDepartmentId());
            map.put("valid", true);
            map.put("orderSql", "t.id desc");
            map.put("code", "guding-laodaixin");
            map.put("catagory", "1");
            List<Discount> discounts = discountRepository.selectAll(map);
            if(discounts.size()>0){
                discount = discounts.get(0);
                RestTemplate template = new RestTemplate();
                Map param = new HashMap();
                param.put("scene",rider.getId()+":"+discount.getId());
                param.put("page","pages/map/map");
                String re = template.postForObject("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + tokenMap.get("access_token"),param, String.class);
                response.setContentType("image/jpeg");
                response.setHeader("Pragma","no-cache");
                response.setHeader("Cache-Control","no-cache");
                response.setIntHeader("Expires",-1);
                try( OutputStream os  = response.getOutputStream()){
                    os.write(re.getBytes("iso8859-1"));
                    os.flush();
//                    os.close();
                }
            }
        }

    }
    @GetMapping("/disCount/use/{id}")
    public ResponseEntity<Object> useDiscount(@PathVariable Integer id) {
        DiscountLog log = discountLogRepository.selectByPrimaryKey(id);
        DiscountLog update = new DiscountLog();
        update.setId(log.getId());
        update.setStatus(1);
        update.setBeginDate(new Date().getTime());
        discountLogRepository.updateByPrimaryKeySelective(update);
        Rider rider = riderRepository.selectByPrimaryKey(log.getRiderId());
        Rider updateRider = new Rider();
        updateRider.setId(rider.getId());
        updateRider.setEndDate(rider.getEndDate() + (Long.valueOf(1000 * 24 * 60*60) * log.getDiscountMoney().longValue()));
        riderRepository.updateByPrimaryKeySelective(updateRider);
        rider.setEndDate(updateRider.getEndDate());


        PayLog payLog = new PayLog();
        payLog.setRiderId(rider.getId());
        payLog.setPhone(rider.getPhone());
        payLog.setRiderName(rider.getName());
        payLog.setPackageName(log.getDiscount().getName());
        payLog.setPackageId(log.getId());
        payLog.setMemo(rider.getCompanyName());
        payLog.setRiderName(rider.getName());
        payLog.setPayMoney(log.getDiscountMoney());
        payLog.setCreateDate(new Date().getTime());
        payLog.setBeginDate(new Date().getTime());
        payLog.setEndDate(new Date().getTime()+(Long.valueOf(1000 * 24 * 60*60) * log.getDiscountMoney().longValue()));
        payLog.setCatagory("延时优惠券");
        payLog.setStatus(1);
        payLogRepository.insert(payLog);
        return new ResponseEntity<Object>(rider,HttpStatus.OK);
    }
    @GetMapping("/depositType/{id}")
    public ResponseEntity<Object> getDepositType(@PathVariable Integer id, @RequestParam(value = "name", required = false, defaultValue = "") String name,
                                                 @RequestParam(value = "rentType", required = true, defaultValue = "") Integer rentType) {
        Rider rider = riderRepository.selectByPrimaryKey(id);
        if (rider != null) {
//            if (rider.getState() == 1) {
//                return new ResponseEntity<Object>(ErrorCode.defaultInstance("您已经核准激活,请联系商家"), HttpStatus.BAD_GATEWAY);
//            }
            Map map = new HashMap();
            map.put("departmentId", rider.getDepartmentId());
            map.put("valid", true);
            map.put("rentTypeId", rentType);
            List<Deposit> list = depositRepository.selectAll(map);
            if (list.size() == 0) {
                return new ResponseEntity<Object>("没有押金设置,请联系管理员",HttpStatus.INTERNAL_SERVER_ERROR);
            }
            if (list.size() > 1) {
                return new ResponseEntity<Object>("有多个押金设置,请联系管理员",HttpStatus.INTERNAL_SERVER_ERROR);
            }
            Rider uprider = new Rider();
            uprider.setId(rider.getId());
            uprider.setRentType(rentType);
            rider.setRentType(rentType);
            riderRepository.updateByPrimaryKeySelective(uprider);
            map.put("catagory", 1);
            map.put("orderSql", "t.id desc");
            map.put("riderId", rider.getId());
            map.put("status", 0);
            List<DiscountLog> discountLogs = discountLogRepository.selectAll(map);

            rider.setDepositTypeList(list);
            rider.setDiscountLogList(discountLogs);
        }
        return new ResponseEntity<Object>(rider,HttpStatus.OK);
    }
    @RequestMapping("/paylog/list")
    public List<PayLog> gotoPayLogList(@RequestParam(required = false) HashMap<String, Object> queryParam, Page page, HttpServletResponse response,
                                           HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        queryParam.put("status", 1);
        List<PayLog> list = payLogRepository.selectListByPage(queryParam);
        return list;
    }
    public Double GetShotLocal(Double lat, Double lon, Double initlat,Double initlon) {
        Double x = (initlat - lat) * (initlat - lat);
        Double y = (initlon - lon) * (initlon - lon);
        Double z = Math.sqrt(x + y);
        return z;
    }
    public Double GetShotLocal(String lat, String lon, String initlat,String initlon) {

        return this.GetShotLocal(Double.valueOf(lat),Double.valueOf(lon),Double.valueOf(initlat),Double.valueOf(initlon));
    }
    @RequestMapping("/department/list")
    public List<Department> getDepartmentList(@RequestParam(required = false) HashMap<String, Object> queryParam, Page page, HttpServletResponse response,
                                              HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        Object longitude = queryParam.get("longitude");
        Object latitude = queryParam.get("latitude");
        if (queryParam.containsKey("longitude")) {
            queryParam.remove("longitude");
        }
        if (queryParam.containsKey("latitude")) {
            queryParam.remove("latitude");
        }
        queryParam.put("valid", true);
        queryParam.put("orderSql", "t.ordinal");
        List<Department> list = departmentRepository.selectAll(queryParam);
        Department current = null;
        Double distance = Double.MAX_VALUE;
        if (longitude != null && latitude != null) {
            for (Department department : list) {
                if (department.getLatitude() != null && department.getLongitude() != null) {
                    Double value = GetShotLocal(latitude.toString(), longitude.toString(), department.getLatitude(), department.getLongitude());
                    if (value < distance) {
                        distance = value;
                        current = department;
                    }
                }
            }
        }
        if (current != null) {
            list = new ArrayList<>();
            list.add(current);
        }
        DataDic dic1 = new DataDic();
        dic1.setName("单电池租赁");
        dic1.setId(1);
        DataDic dic2 = new DataDic();
        dic2.setName("整车租赁");
        dic2.setId(2);
        List<DataDic> dicList = new ArrayList<>();
        dicList.add(dic1);
        dicList.add(dic2);
        list.get(0).setRentTypeList(dicList);
        return list;
    }
    @RequestMapping("/company/list")
    public List<Company> getCompanyList(@RequestParam(required = false) HashMap<String, Object> queryParam, Page page, HttpServletResponse response,
                                        HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        queryParam.put("valid", true);
        List<Company> list = companyRepository.selectAll(queryParam);
        return list;
    }
    @RequestMapping("/company/getCode")
    public SendResult getCode(Integer companyId,Integer riderId, Page page, HttpServletResponse response,
                                        HttpServletRequest request, Model model) {
        Company company = companyRepository.selectByPrimaryKey(companyId);
        Rider rider = riderRepository.selectByPrimaryKey(riderId);
        Map<String, Object> param = new HashMap<>();
        param.put("companyId",companyId );
        param.put("state",RiderStatus.CANCEL.value );
        Integer count = riderRepository.selectCount(param);
        SendResult sr;

        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(10);
        }
        String sendsmsurl = "http://dev.hspaas.cn:8080/sms/send";
        String appkey = "hsV334o9K0POGF";
        String appsecret = "2a57e536b5d641f5dd107a276a28661f";
        String phonenumber = company.getPhone();
        if (count >= company.getLimitCount()) {
            sr = new SendResult();
            sr.setCode("-1");
            sr.setMessage("集团用户已到达上限："+company.getLimitCount());
            RongHeSmsClientSend.sendSms(sendsmsurl,
                    appkey, appsecret, phonenumber, "集团用户已到达上限："+company.getLimitCount());
            return sr;
        }
        String msgContent = "【i换电】骑手"+rider.getName()+"-"+rider.getPhone()+",发来激活申请，验证码是"+result+"。";
        String sendResult = RongHeSmsClientSend.sendSms(sendsmsurl,
                appkey, appsecret, phonenumber, msgContent);
        //{"code":"0","message":"调用成功","fee":"1","sid":"2278705166943258630"}
        System.out.println(sendResult);
        sr = JSON.parseObject(sendResult,SendResult.class);
        sr.setValidcode(result);
        log.debug(sendResult);
        return sr;
    }
    public static class SendResult{
        public String code;
        public String message;
        public String fee;
        public String sid;
        public String validcode;

        public String getValidcode() {
            return validcode;
        }

        public void setValidcode(String validcode) {
            this.validcode = validcode;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getFee() {
            return fee;
        }

        public void setFee(String fee) {
            this.fee = fee;
        }

        public String getSid() {
            return sid;
        }

        public void setSid(String sid) {
            this.sid = sid;
        }
    }
    @GetMapping("/getPositions")
    public List<BatteryCabinet> getPositoins(Integer riderId) {
        Map<String, Object> params = new HashMap<>();
        params.put("endSql", "t.longitude>0 and t.latitude>0");
        Rider rider;
        if (riderId != null) {
            rider = riderRepository.selectByPrimaryKey(riderId);
            params.put("departmentId", rider.getDepartmentId());
        }
        List<BatteryCabinet> cabinets = batteryCabinetRepository.selectAll(params);
        RestTemplate restTemplate = new RestTemplate();
        StringBuilder sb = new StringBuilder();
        sb.append("http://47.105.65.229:9898/queryAllState");
        String xl = restTemplate.getForObject(sb.toString(), String.class);
        LockerResult postions = JSON.parseObject(xl, LockerResult.class);
        Map<String, Integer> counts = new HashMap<>();
        for (LockerResultItem item : postions.getAllState()) {
            counts.put(item.getGid(), Integer.valueOf(item.getCount().get("okCount").toString()));
        }
        Map<String, BatteryCabinet> countMap = new HashMap<>();
        for (BatteryCabinet c : cabinets) {
            if (counts.containsKey(c.getNo())) {
                c.setCount(counts.get(c.getNo()));
                BatteryCabinet bc;
                if(StringUtils.isNotBlank(c.getAddress())){
                    if(countMap.containsKey(c.getAddress())){
                        bc = countMap.get(c.getAddress());
                        bc.setCount(bc.getCount()+c.getCount());
                    }else{
                        bc = c;
                    }
                    countMap.put(c.getAddress(), bc);
                }
            }
        }
        List list = new ArrayList<>();
        list.addAll(countMap.values());
        return list;
    }

    @GetMapping("/loginByWechat/{uionid}")
    public ResponseEntity<Object> getRiderByWechat(@PathVariable String uionid, String name) {
        Map param = WXPayAgent.getOpenId(uionid);
        if (param.containsKey("errcode")) {

            param.keySet().forEach((x) -> {
                log.debug(x + "========" + param.get(x));
            });
            return new ResponseEntity<Object>(ErrorCode.defaultInstance("小程序用户认证异常"), HttpStatus.BAD_GATEWAY);
        }
        Map riderMap = new HashMap();
        riderMap.put("unionid", param.get("openid"));
        riderMap.put("endSql", "t.departmentId is not null");
        List<Rider> riderList = riderRepository.selectAll(riderMap);
        Rider rider = null;
        if (riderList.size() > 0) {
            rider = riderList.get(0);
            if (rider.getCompanyId() != null) {
                if (rider.getJhDate() == null) {
                    rider.setJh(false);
                }else{
                    if (new Date().getTime() > rider.getJhDate()) {
                        rider.setJh(false);
                    }
                }

            }
        }
        // TODO: 2019/2/9
        if (rider != null) {
            UsernamePasswordToken token = new UsernamePasswordToken(rider.getUnionid(), rider.getId().toString(), false);
            SecurityUtils.getSubject().login(token);
            ShiroUtil.setRider(rider);
        } else {
            rider = new Rider();
            rider.setUnionid((String) param.get("openid"));
            rider.setState(RiderStatus.INIT.getValue());
            rider.setBalance(new BigDecimal(0));
            riderRepository.insertSelective(rider);
            rider.setId(rider.getId());

        }
//        Map<String, Object> params = new HashMap<>();
//        params.put("endSql", "t.longitude>0 and t.latitude>0");
//
//        List<BatteryCabinet> cabinets = batteryCabinetRepository.selectAll(params);
//        rider.setCabinets(cabinets);

        return new ResponseEntity<Object>(rider, HttpStatus.OK);
    }

    @GetMapping("/getWxkey/{code}")
    public ResponseEntity<Map> getWxkey(@PathVariable String code, String name) {
        RestTemplate restTemplate = new RestTemplate();
        StringBuilder sb = new StringBuilder();
        sb.append("https://api.weixin.qq.com/sns/jscode2session");
        sb.append("?appid=").append("wx899777e9089a358d");//wx899777e9089a358d
        sb.append("&secret=").append("257ceb9d0a306b601950297e691f4bca");
        sb.append("&js_code=").append("0711ivNx0vK2Nh1KPNPx0LxENx01ivNE11");
        sb.append("&grant_type=authorization_code");
        String xl = restTemplate.getForObject(sb.toString(), String.class);
        Map map = JSON.parseObject(xl, HashMap.class);
        if (map.containsKey("errcode")) {//{errcode=40029, errmsg=invalid code, hints: [ req_id: 3Bpc04922273 ]}
            return new ResponseEntity<Map>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Map>(map, HttpStatus.OK);
    }
    @PostMapping(value = "/valid.do")
    public Rider validCompany(Integer riderId,Integer companyId,HttpServletRequest request, HttpServletResponse response) throws Exception {
        Rider rider = riderRepository.selectByPrimaryKey(riderId);
        PayLog payLog = new PayLog();
        payLog.setRiderId(rider.getId());
        payLog.setPhone(rider.getPhone());
        payLog.setRiderName(rider.getName());
        payLog.setPackageName("集团用户激活");
        payLog.setPackageId(rider.getId());
        payLog.setMemo(rider.getCompanyName());
        payLog.setRiderName(rider.getName());
        payLog.setPayMoney(BigDecimal.ZERO);
        payLog.setCreateDate(new Date().getTime());
        payLog.setBeginDate(new Date().getTime());
        payLog.setEndDate(new Date().getTime()+Long.valueOf(30*24)*60*60*1000);
        payLog.setCatagory("集团用户激活");
        payLog.setStatus(1);
        payLogRepository.insert(payLog);
        Company company = companyRepository.selectByPrimaryKey(companyId);
        Rider update = new Rider();
        update.setCompanyId(companyId);
        update.setCompanyName(company.getName());
        update.setState(RiderStatus.CANCEL.value);
        update.setJhDate(new Date().getTime()+Long.valueOf(30*24)*60*60*1000);
//        update.setEndDate(new Date().getTime()+Long.valueOf(30*24)*60*60*1000);
        update.setId(rider.getId());
        riderRepository.updateByPrimaryKeySelective(update);
        rider = riderRepository.selectByPrimaryKey(riderId);
        return rider;
    }

    @RequestMapping(value = "/refundNotify.do", produces = "text/html;charset=UTF-8", method = {RequestMethod.POST})
    public void refundNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 解析结果存储在HashMap
        Map<String, String> map = new HashMap<String, String>();
        InputStream inputStream = request.getInputStream();

        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
        log.debug("===return_code===" + map.get("return_code"));
        log.debug("===return_msg===" + map.get("return_msg"));
        log.debug("===out_trade_no===" + map.get("out_trade_no"));
        //验证签名的过程

        //判断是否支付成功
        if (map.get("return_code").equals("SUCCESS")) {
            String req_info = map.get("req_info");
            //解密信息
            String info = AESUtil.decryptData(req_info);
            //将解密数据转化为Map
            SAXBuilder builder = new SAXBuilder();

            Document doc = DocumentHelper.parseText(info);

            Element element = doc.getRootElement();
            List<Element> list = element.elements();
            for (Element e : list) {
                log.debug("====="+e.getName()+":"+e.getText());
                map.put(e.getName(), e.getText());
            }

            /**
             *支付成功之后的业务处理
             */
            String orderId = map.get("out_refund_no");
            String transaction_id = map.get("transaction_id");
            RefundLog refundLog = refundLogRepository.selectByPrimaryKey(Integer.valueOf(orderId));
            PayLog payLog = payLogRepository.selectByPrimaryKey(refundLog.getPayLogId());
            if (payLog != null) {

                RefundLog updateRefundLog = new RefundLog();
                updateRefundLog.setId(refundLog.getId());
                updateRefundLog.setStatus(1);

                PayLog updateOrder = new PayLog();
                updateOrder.setId(payLog.getId());
                BigDecimal refundedMoney = payLog.getRefundMoney()==null?BigDecimal.ZERO:payLog.getRefundMoney();
                updateOrder.setRefundMoney(refundedMoney.add(refundLog.getRefundMoney()));
                payLogRepository.updateByPrimaryKeySelective(updateOrder);
                refundLogRepository.updateByPrimaryKeySelective(updateRefundLog);
            }
            // 释放资源
            inputStream.close();
            inputStream = null;
            Writer out = response.getWriter();
            out.write("<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>");
            out.close();

        } else if (map.get("return_code").equals("FAIL")) {
            /**
             *支付失败后的业务处理
             */
            // 释放资源
            inputStream.close();
            inputStream = null;
        }


    }
    @RequestMapping(value = "/notify.do", produces = "text/html;charset=UTF-8", method = {RequestMethod.POST})
    public void returnmsg(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 解析结果存储在HashMap
        Map<String, String> map = new HashMap<String, String>();
        InputStream inputStream = request.getInputStream();

        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
        log.debug("===return_code===" + map.get("return_code"));
        log.debug("===return_msg===" + map.get("return_msg"));
        log.debug("===out_trade_no===" + map.get("out_trade_no"));
        //验证签名的过程

        //判断是否支付成功
        if (map.get("return_code").equals("SUCCESS")) {

            /**
             *支付成功之后的业务处理
             */
            String orderId = map.get("out_trade_no");
            String transaction_id = map.get("transaction_id");

            PayLog order = payLogRepository.selectByPrimaryKey(Integer.valueOf(orderId));
            if (order != null) {
                if(StringUtils.isNotBlank(order.getDiscountIds())){
                    String[] ids = order.getDiscountIds().split(",");
                    for (String id : ids) {
                        DiscountLog discountLog = discountLogRepository.selectByPrimaryKey(Integer.valueOf(id));
                        if (discountLog != null) {
                            DiscountLog updataLog = new DiscountLog();
                            updataLog.setId(discountLog.getId());
                            updataLog.setEndDate(new Date().getTime());
                            updataLog.setStatus(1);
                            discountLogRepository.updateByPrimaryKeySelective(updataLog);
                        }
                    }
                }
                Rider rider = riderRepository.selectByPrimaryKey(order.getRiderId());
                Rider update = new Rider();
                PayLog updateOrder = new PayLog();
                if ("押金".equals(order.getCatagory())) {
                    update.setState(RiderStatus.CANCEL.value);
                    rider.setCompanyName(null);
                    rider.setCompanyId(null);
                    rider.setJhDate(null);
                    riderRepository.updateByPrimaryKey(rider);
                }else if ("充值".equals(order.getCatagory())) {
                    update.setEndDate(order.getEndDate());
                }else if ("充值其它".equals(order.getCatagory())) {

                }
                updateOrder.setId(order.getId());
                updateOrder.setTransaction_id(transaction_id);
                updateOrder.setStatus(1);
                payLogRepository.updateByPrimaryKeySelective(updateOrder);
                update.setId(rider.getId());
                //总金额
                BigDecimal begin = rider.getBalance()==null?new BigDecimal(0):rider.getBalance();
                update.setBalance(begin.add(order.getPayMoney()));
                riderRepository.updateByPrimaryKeySelective(update);
            }
            // 释放资源
            inputStream.close();
            inputStream = null;
            Writer out = response.getWriter();
            out.write("<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>");
            out.close();

        } else if (map.get("return_code").equals("FAIL")) {

            /**
             *支付失败后的业务处理
             */
            // 释放资源
            inputStream.close();
            inputStream = null;
        }


    }
    @PostMapping("/recharge")
    public ResponseEntity<Object> recharge(@RequestBody PayLog payLog) {
        Map map = null;
        try {
            payLog.setCreateDate(new Date().getTime());
            payLog.setStatus(0);
            Rider rider = riderRepository.selectByPrimaryKey(payLog.getRiderId());
            BigDecimal discountMoneys = BigDecimal.ZERO;
            BigDecimal payMoneys = BigDecimal.ZERO;
            if (StringUtils.isNotBlank(payLog.getDiscountIds())) {
                String[] ids = payLog.getDiscountIds().split(",");
                for (String id : ids) {
                    DiscountLog discountLog = discountLogRepository.selectByPrimaryKey(Integer.valueOf(id));
                    if(discountLog==null||!discountLog.getValid()||discountLog.getStatus()==1){
                        log.error("优惠券无效，请重新选择:"+discountLog.getId());
                        return new ResponseEntity<Object>(ErrorCode.defaultInstance("优惠券无效，请重新选择:"+discountLog.getId()), HttpStatus.INTERNAL_SERVER_ERROR);
                    }
                    discountMoneys = discountMoneys.add(discountLog.getDiscountMoney());
                }
            }
            //押金
            if ("押金".equals(payLog.getCatagory())) {
                Deposit deposit = depositRepository.selectByPrimaryKey(payLog.getPackageId());
                if (deposit == null) {
                    log.error("找不到押金对象:"+payLog.getPackageId());
                    return new ResponseEntity<Object>(ErrorCode.defaultInstance("找不到押金对象:"+payLog.getPackageId()), HttpStatus.INTERNAL_SERVER_ERROR);
                }
                payMoneys = new BigDecimal(deposit.getValue());
                payLog.setPackageName(deposit.getName());
                payLog.setMemo(deposit.getCatagory().equals("1")?"单电池租赁":"整车租赁");
            }else if ("充值".equals(payLog.getCatagory())) {
                if (payLog.getPackageId() == -1) {
                    log.error("缴费类型错误，充值错误-1");
                    return new ResponseEntity<Object>(ErrorCode.defaultInstance("缴费类型错误，充值错误-1"), HttpStatus.INTERNAL_SERVER_ERROR);
                }else{
                    Charge charge = chargeRepository.selectByPrimaryKey(payLog.getPackageId());
                    if (charge == null) {
                        log.error("找不到充值对象:"+payLog.getPackageId());
                        return new ResponseEntity<Object>(ErrorCode.defaultInstance("找不到充值对象:"+payLog.getPackageId()), HttpStatus.INTERNAL_SERVER_ERROR);
                    }
                    payMoneys = new BigDecimal(charge.getValue());
                    if (rider.getEndDate() == null||rider.getEndDate()<(new Date().getTime())) {
                        payLog.setBeginDate(new Date().getTime());
                    }else{
                        payLog.setBeginDate(rider.getEndDate()+24*60*60*1000);
                    }
                    payLog.setPackageName(charge.getName());
                    payLog.setEndDate(payLog.getBeginDate()+Long.valueOf(charge.getCode())*30*24*60*60*1000);
                }

            }else if ("充值其它".equals(payLog.getCatagory())) {
                if (payLog.getPackageId() == -1) {
                    payMoneys = payLog.getPayMoney().add(payLog.getDiscountMoney());
                }else{
                    log.error("缴费类型错误，充值其它错误非-1");
                    return new ResponseEntity<Object>(ErrorCode.defaultInstance("缴费类型错误，充值其它错误非-1"), HttpStatus.INTERNAL_SERVER_ERROR);
                }

            }else{
                log.error("缴费类型错误");
                return new ResponseEntity<Object>(ErrorCode.defaultInstance("缴费类型错误"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
            payMoneys = payMoneys.subtract(discountMoneys);
            if (payMoneys.doubleValue() != payLog.getPayMoney().doubleValue()) {
                log.error("前后台金额不符");
                return new ResponseEntity<Object>(ErrorCode.defaultInstance("前后台金额不符"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
            payLog.setPhone(rider.getPhone());
            payLog.setRiderName(rider.getName());
            payLogRepository.insert(payLog);

            WXPayAgent dodo = new WXPayAgent( payLog.getId().toString(), payLog.getPayMoney().multiply(new BigDecimal("100")).intValue());
            map = dodo.doXcxUnifiedOrder(payLog.getOpenId());

//            this.test_notify(payLog.getId());



        } catch (Exception e) {
            log.error(e.toString(), e);
            return new ResponseEntity<Object>(ErrorCode.defaultInstance("充值失败"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Object>(map, HttpStatus.OK);
    }
    private void test_notify(Integer orderId){
        PayLog order = payLogRepository.selectByPrimaryKey(Integer.valueOf(orderId));
        if (order != null) {
            if(StringUtils.isNotBlank(order.getDiscountIds())){
                String[] ids = order.getDiscountIds().split(",");
                for (String id : ids) {
                    DiscountLog discountLog = discountLogRepository.selectByPrimaryKey(Integer.valueOf(id));
                    if (discountLog != null) {
                        DiscountLog updataLog = new DiscountLog();
                        updataLog.setId(discountLog.getId());
                        updataLog.setEndDate(new Date().getTime());
                        updataLog.setStatus(1);
                        discountLogRepository.updateByPrimaryKeySelective(updataLog);
                    }
                }
            }
            Rider rider = riderRepository.selectByPrimaryKey(order.getRiderId());
            Rider update = new Rider();
            PayLog updateOrder = new PayLog();
            if ("押金".equals(order.getCatagory())) {
                update.setState(RiderStatus.CANCEL.value);
                rider.setCompanyName(null);
                rider.setCompanyId(null);
                rider.setJhDate(null);
                riderRepository.updateByPrimaryKey(rider);
            }else if ("充值".equals(order.getCatagory())) {
                update.setEndDate(order.getEndDate());
            }else if ("充值其它".equals(order.getCatagory())) {

            }
            updateOrder.setId(order.getId());
            updateOrder.setStatus(1);
            payLogRepository.updateByPrimaryKeySelective(updateOrder);
            update.setId(rider.getId());
            //总金额
            BigDecimal begin = rider.getBalance()==null?new BigDecimal(0):rider.getBalance();
            update.setBalance(begin.add(order.getPayMoney()));
            riderRepository.updateByPrimaryKeySelective(update);
        }
    }
    @PostMapping("/recharge_bk")
    public ResponseEntity<Object> recharge_bk(@RequestBody PayLog payLog) {
        Map map = null;
        try {
            payLog.setCreateDate(new Date().getTime());
            payLog.setStatus(0);
            Rider rider = riderRepository.selectByPrimaryKey(payLog.getRiderId());
            payLog.setPhone(rider.getPhone());
            payLog.setRiderName(rider.getName());
            payLogRepository.insert(payLog);
            WXPayAgent dodo = new WXPayAgent( payLog.getId().toString(), payLog.getPayMoney().multiply(payLog.getPayMoney().multiply(new BigDecimal("100"))).intValue());
            map = dodo.doXcxUnifiedOrder(payLog.getOpenId());
        } catch (Exception e) {
            log.error(e.toString(), e);
            return new ResponseEntity<Object>(ErrorCode.defaultInstance("充值失败"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Object>(map, HttpStatus.OK);
    }

    @PostMapping("/uploadCard")
    public ResponseEntity<Object> uploadCard(@RequestParam(value = "file",required = false) MultipartFile file,Integer riderId, HttpServletRequest request, HttpServletResponse response) {
        Map map = new HashMap();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName = ImageUploadUtil.upload(request, file);
            String imageContextPath = request.getContextPath();
            imageContextPath = imageContextPath + "/fileUpload/" + sdf.format(new Date()) + "/" + fileName;
            map.put("fileName", imageContextPath);

        } catch (Exception e) {
            log.error(e.toString(), e);
            return new ResponseEntity<Object>(ErrorCode.defaultInstance("上传失败"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Object>(map, HttpStatus.OK);
    }

    @PostMapping("")
    public ResponseEntity addRider(@RequestBody Rider rider, HttpServletRequest request) {
        try {
            rider.setState(RiderStatus.NORMAL.getValue());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            rider.setCreateDate(sdf.format(new Date()));
            riderRepository.updateByPrimaryKeySelective(rider);
            Map map = new HashMap();
            map.put("departmentId", rider.getDepartmentId());
            map.put("valid", true);
            map.put("orderSql", "t.id desc");
            map.put("catagory", "1");
            map.put("code", "guding-xin");
            List<Discount> xins = discountRepository.selectAll(map);
            Rider xin = riderRepository.selectByPrimaryKey(rider.getId());
            if (xins.size() > 0) {
                Discount discount1 = xins.get(0);
                DiscountLog log1 = new DiscountLog();
                log1.setRiderName(xin.getName());
                log1.setRiderId(xin.getId());
                log1.setPhone(xin.getPhone());
                log1.setDiscountId(discount1.getId());
                log1.setCreateDate(new Date().getTime());
                log1.setDiscountMoney(discount1.getValue());
                log1.setCatagory(discount1.getCatagory());
                log1.setMemo("新骑手注册");
                log1.init();
                discountLogRepository.insert(log1);
            }
            if(StringUtils.isNotBlank(rider.getScene())){
                map.put("code", "guding-laodaixin");
                List<Discount> discounts = discountRepository.selectAll(map);
                String[] arrs = rider.getScene().split(":");
                Rider source = riderRepository.selectByPrimaryKey(Integer.valueOf(arrs[0]));

                if (discounts.size()>0&&xins.size()>0) {
                    Discount discount = discounts.get(0);
                    DiscountLog log = new DiscountLog();
                    log.setRiderName(source.getName());
                    log.setRiderId(source.getId());
                    log.setPhone(source.getPhone());
                    log.setDiscountId(discount.getId());
                    log.setCreateDate(new Date().getTime());
                    log.setDiscountMoney(discount.getValue());
                    log.setCatagory(discount.getCatagory());
                    log.setMemo("老带新【新骑手:"+xin.getName()+xin.getPhone()+"-"+xin.getId()+"】");
                    log.init();
                    discountLogRepository.insert(log);

                }
            }
            UsernamePasswordToken token = new UsernamePasswordToken(rider.getUnionid(), rider.getId().toString(), false);
            SecurityUtils.getSubject().login(token);
            ShiroUtil.setRider(rider);
        } catch (BusinessException e) {
            return new ResponseEntity(e.toString(), HttpStatus.CONFLICT);
        } catch (Exception e) {
            return new ResponseEntity(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(rider, HttpStatus.OK);
    }
    @PostMapping("/upload")
    public ResponseEntity uploadRider(@RequestBody Rider rider, HttpServletRequest request) {
        try {
            riderRepository.updateByPrimaryKeySelective(rider);
        } catch (BusinessException e) {
            return new ResponseEntity(e.toString(), HttpStatus.CONFLICT);
        } catch (Exception e) {
            return new ResponseEntity(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(rider, HttpStatus.OK);
    }

    @ExceptionHandler({IOException.class, Exception.class})
    public ResponseEntity<String> handle(IOException ex, Exception x) {
        return new ResponseEntity<String>("IOException", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @Value("${system.jsms.appkey}")
    private String appkey;
    @Value("${system.jsms.masterSecret}")
    private String masterSecret;

    @GetMapping("/getGJCode/{phone}")
    public ResponseEntity getJGCode(@PathVariable String phone, HttpServletRequest request) {
        Map map = new HashMap();
        try {
            SMSClient client = new SMSClient(masterSecret, appkey);
            SMSPayload payload
                    = SMSPayload.newBuilder()
                    .setMobileNumber(phone)
                    .setTempId(1)
                    .build();
            SendSMSResult res = client.sendSMSCode(payload);
            log.info(res.toString());
            return new ResponseEntity<SendSMSResult>(res, HttpStatus.OK);
        } catch (BusinessException e) {

            return new ResponseEntity(e.toString(), HttpStatus.CONFLICT);
        } catch (APIConnectionException e) {

            log.error("服务器连接错误,稍后再试!", e);
            return new ResponseEntity(e, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (APIRequestException e) {

            log.error("系统异常,请求错误!", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
            return new ResponseEntity(e, HttpStatus.CONFLICT);
        }
        //return new ResponseEntity<SendSMSResult>(res, HttpStatus.OK);
    }

    @GetMapping("/validGJCode")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity validGJCode(@RequestParam(value = "msgId", required = false) String msgId,
                                      @RequestParam(value = "code", required = false) String code,
                                      HttpServletRequest request) {
        try {
            SMSClient client = new SMSClient(masterSecret, appkey);
            //验证验证码
            ValidSMSResult res = client.sendValidSMSCode(msgId, code);
            return new ResponseEntity<ValidSMSResult>(res, HttpStatus.OK);

        } catch (BusinessException e) {

            return new ResponseEntity(e.toString(), HttpStatus.CONFLICT);
        } catch (APIConnectionException e) {

            log.error("服务器连接错误,稍后再试!", e);
            return new ResponseEntity(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (APIRequestException e) {

            log.error("系统异常,请求错误!", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
            // return new ResponseEntity(e.toString(), HttpStatus.CONFLICT);
            return new ResponseEntity(e, HttpStatus.CONFLICT);
        }
    }

}
